<template>
  <view>
    <view class="flex align-center justify-center relative h-120 sticky z-3" id="container" v-if="isManagerOrAdmin"
      :style="{ top: `${top}px` }">
      <!--骨架屏-->
      <view v-if="loading">
        <view class="flex align-center justify-center pb-30 pt-50">
          <view class="h-60 w-200 br-5 bg-f4f7f4"> </view>
          <view class="w-30 h-5 br-5 m-lr-10"></view>
          <view class="h-60 w-200 br-5 bg-f4f7f4"></view>
          <view class="h-60 w-180 br-5 bg-f4f7f4 ml-20"></view>
        </view>
      </view>

      <date-picker v-if="!loading" class="datePicker z-999" @changeTime="changeTime">
      </date-picker>
      <u-dropdown v-if="!loading" ref="uDropdown" height="144" inactive-color="#2D8CF0" :close-on-click-mask="false"
        menu-icon="arrow-down-fill">
        <u-dropdown-item :title="title">
          <view class="bg-fff pb-30">
            <u-checkbox-group class="w-full" size="40">
              <view class="w-full flex flex-column p-lr-20">
                <view v-for="(item, index) in checkedStatusList" :key="index"
                  class="h-90 border-333333 br-10 pl-25 w-full flex align-center mb-20">
                  <u-checkbox class="w-full flex" :name="item.value" :disabled="false" v-model="item.checked"
                    shape="circle" active-color="#19BE6B">
                    <text class="color-333333 fz-32 ml-30"> {{ item.label }} </text>
                  </u-checkbox>
                </view>
              </view>
            </u-checkbox-group>
            <view v-if="isSelectChecked" class="m-lr-20 h-100 br-10 bg-2D8CF0 text-center fz-32 lh-100 color-fff"
              @tap="confirmStatus">
              <text>确定</text>
            </view>
            <view v-else class="m-lr-20 h-100 br-10 bg-BEBEBE text-center fz-32 lh-100 color-fff">
              <text>确定</text>
            </view>
          </view>
        </u-dropdown-item>
      </u-dropdown>
    </view>
    <!--骨架屏-->
    <list-skeleton v-if="loading"></list-skeleton>

    <view :style="{ minHeight: `calc(100vh - ${top}px - ${safeAreaInsets}px - 338rpx)` }">
      <view v-if="fixList.length && !loading">
        <view class="flex" v-for="item in fixList" :key="item.workOrderId" @longpress="handleLongpress">
          <view class="w-50 flex align-center ml-20" v-if="isLongPress" @tap.stop="">
            <u-checkbox size="50" v-model="item.checked"></u-checkbox>
          </view>
          <view class="m-lr-20 mb-30 pl-20 p-tb-12 flex1 flex align-center justify-between bg-E9F8FF br-10 oh"
            @tap="clickItem(item)">

            <view class="flex flex-column oh">
              <text class="fz-40 font-bold lh-56 mt-12 break-all text-ellipsis">{{ item.deviceName || '-' }}</text>
              <text class="fz-28 lh-40 mt-20 text-ellipsis" v-if="!isShowField(item.status)">
                维修工程师: {{ item.repairStaff || '-' }}
              </text>
              <text class="fz-28 lh-40 mt-20 text-ellipsis" v-if="isShowField(item.status)">
                报修人: {{ item.initiator || '-' }}
              </text>
              <text class="flex mt-20 fz-28 lh-40">
                报修时间：{{ item.createTime }}
              </text>
              <view class="fz-28 mt-20" v-if="!isShowField(item.status) && item.status !== REP_WORK_ORDER_STATUS.REJECTED.value">
                维修开始时间：{{ item.startTime }}
              </view>
              <view class="flex mt-20 fz-28" v-if="item.status === REP_WORK_ORDER_STATUS.DONE.value">
                维修结束时间：{{ item.endTime }}
              </view>
            </view>

            <view class="relative mr-30">
              <CustomCircleProgress :border-width="8" :size="128" :percent="getOrderPercentage(item.status)"
                :active-color="getOrderStatusColor(item.status)">
                <view class="h-full w-full lh-center" :style="{ 'color': getOrderStatusColor(item.status) }">
                  <text class="fz-30">{{ getStatusName(item.status) }}</text>
                </view>
              </CustomCircleProgress>
            </view>
          </view>
        </view>

      </view>
      <empty-icon v-if="fixList.length===0 && !loading"></empty-icon>
    </view>

    <view class="flex align-center justify-between h-120 sticky bottom-100 bg-fff z-10 p-lr-50" v-if="isLongPress"
      :style="{ bottom: `calc(100rpx + ${safeAreaInsets}px)` }">
      <view class="h-60 w-120 br-5 border-2D8CF0 fz-28 color-2D8CF0 lh-60 text-center" @tap="cancleLongPress">
        <text>取消</text>
      </view>
      <view class="flex">
        <view class="h-60 w-120 br-5 border-2D8CF0 fz-28 color-fff lh-60 text-center"
          :class="isAllowDispatch ? 'allowDispatch' : 'disAllowDispatch'" @tap="dispatch">
          <text>派单</text>
        </view>
      </view>
    </view>

    <!-- 数据未填提示 -->
    <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" mask-close-able v-model="errorShow">
      <view class="h-150 font-bold flex align-center justify-center" >
        <image class="mr-20 w-38 h-38" src="@/static/images/mine/error.png"></image>
        <view class="fz-30 color-333333 err-text">工单信息不完整，请通过编辑补充</view>
      </view>
    </u-modal>

  </view>
</template>

<script>
import CustomCircleProgress from '../../components/CustomCircleProgress'
import DatePicker from "@/components/DatePicker/DatePicker";
import EmptyIcon from "@/components/EmptyIcon/EmptyIcon";
import ListSkeleton from "../../components/ListSkeleton";

import getNavBarHeight from "@/mixins/getNavBarHeight";
import dayjs from '@/libs/dayjs.min.js'

import { REP_WORK_ORDER_STATUS } from '@/utils/dict'
import { list } from "@/api/repair/workOrder";

const repWorkOrderStatusList = Object.keys(REP_WORK_ORDER_STATUS).map(key => REP_WORK_ORDER_STATUS[key])

export default {
  name: "FixAll",
  components: { ListSkeleton, EmptyIcon, DatePicker, CustomCircleProgress },
  mixins: [getNavBarHeight],
  props: ['isManagerOrAdmin'],
  data () {
    return {
      hasNext: false,
      pageNum: 1,
      pageSize: 10,
      startTime: '',
      endTime: '',
      statusList:'',
      fixList: [],
      title: '全部类型',
      loading: true,
      isLongPress: false,
      checkedStatusList: [],
      safeAreaInsets: 0, //底部安全区高度
      errorShow:false
    }
  },
  computed: {
    REP_WORK_ORDER_STATUS () { return REP_WORK_ORDER_STATUS },
    repWorkOrderStatusList () { return repWorkOrderStatusList },
    isSelectChecked(){
      return this.checkedStatusList.some(item=>item.checked)
    },
    selectionList(){
      return this.fixList.filter(item=>item.checked)
    },
    isAllowDispatch () {
      if(this.selectionList.length===0)return false
      return this.selectionList.every(item =>
        item.status !== REP_WORK_ORDER_STATUS.DONE.value && item.status !== REP_WORK_ORDER_STATUS.REJECTED.value && item.status !== REP_WORK_ORDER_STATUS.DO_REPAIR.value
      )
    }
  },

  created () {
    if(this.$store.getters.isFromHome2Work){
      const orderType = this.$store.getters.orderType
      if(orderType==='unDone'){
        const TO_REPAIR = repWorkOrderStatusList[1]
        const DO_REPAIR = repWorkOrderStatusList[3]
        const SUSPEND = repWorkOrderStatusList[4]
        this.checkedStatusList = repWorkOrderStatusList.map(e=>{
          const el = { ...e, checked: false }
          const status = el.value
          if(status === TO_REPAIR.value || status === DO_REPAIR.value || status === SUSPEND.value){
            el.checked = true
          }
          return el
        })
        this.statusList = `${TO_REPAIR.value},${DO_REPAIR.value},${SUSPEND.value}`
        this.title = `${TO_REPAIR.label},${DO_REPAIR.label},${SUSPEND.label}`
      }else if(orderType==='done'){
        const DONE = repWorkOrderStatusList[5]
        this.checkedStatusList = repWorkOrderStatusList.map(e=>{
          const el = { ...e, checked: false }
          if(el.value === DONE.value){
            el.checked = true
          }
          return el
        })
        this.statusList = DONE.value
        this.title = DONE.label
      }
      this.$store.commit('SET_ISFROMHOME2WORK', false)
    }
    else{
      this.checkedStatusList = repWorkOrderStatusList.map(e=>{return { ...e, checked: true }})
    }
    uni.getSystemInfo({
      success: (res) => {
        // #ifdef MP-WEIXIN
        this.safeAreaInsets = res.screenHeight - res.safeArea.bottom
        // #endif
        // #ifndef MP-WEIXIN
        this.safeAreaInsets = res.safeAreaInsets.bottom
        // #endif
      }
    })
    this.doQuery().then(res => {
      this.hasNext = res.hasNext
      this.fixList = res.rows.map(item => {
        return { ...item, checked: false }
      })
    }).finally(() => {
      this.loading = false
    })
  },
  methods: {
    //派单操作(批量分配工程师)
    dispatch () {
      if(this.isAllowDispatch){
        const haveEmptyData = this.selectionList.filter(el=> !(el.hospitalId && el.departmentId && el.companyId && el.deviceName && el.description && el.description.length>0))
        if(haveEmptyData.length > 0){
          this.errorShow = true
        }else{
          const workOrderIdList = this.selectionList.map(item => item.workOrderId)
          const hospitalId = this.selectionList[0].hospitalId
          const companyId = this.selectionList[0].companyId
          this.$tab.navigateTo(`/pages/repair/assign-order?workOrderIdList=${workOrderIdList}&hospitalId=${hospitalId}&companyId=${companyId}&isBatch=1`)
        }
      }
    },
    //取消长按多选
    cancleLongPress () {
      this.fixList.forEach(item => {
        item.checked = false
      })
      this.isLongPress = false
    },
    //长按多选
    handleLongpress () {
      //长按手机震动并且显示复选框
      uni.vibrateShort({
        success: function () { }
      });
      this.isLongPress = true
    },
    //确定选择工单状态
    confirmStatus () {
      const curCheck = this.checkedStatusList.filter(item => item.checked)
      if(curCheck.length===this.checkedStatusList.length){
        this.title = '全部类型'
      }else{
        this.title = curCheck.map(item=>item.label).join(",")
      }
      this.statusList = curCheck.map(item=>item.value).join(",")

      this.pageNum = 1
      this.doQuery().then(res => {
        this.hasNext = res.hasNext
        this.fixList = res.rows.map(item => {
          return { ...item, checked: false }
        })
      })
      this.$refs.uDropdown.close();
    },
    clickItem (item) {
      if (!this.isLongPress) {
        this.loading = true
        let routePath = 'fix-all-order-detail'
        if(item.status === REP_WORK_ORDER_STATUS.TO_ACCEPT.value){
          routePath = "fix-receive-order-detail"
        }
        this.$tab.navigateTo(`/pages/repair/${routePath}?workOrderId=${item.workOrderId}&hospitalId=${item.hospitalId}&status=${item.status}`)
        return;
      }
      else {
        item.checked = !item.checked
      }
    },
    reachBottom () {
      if (this.hasNext) {
        this.pageNum++
        this.doQuery().then(res => {
          this.hasNext = res.hasNext
          this.fixList = [...this.fixList, ...res.rows.map(item => {
            return { ...item, checked: false }
          })]
        })
      }
    },
    changeTime (e) {
      this.pageNum = 1
      this.startTime = e.startTime ? dayjs(e.startTime).format('YYYY-MM-DD') : '';
      this.endTime = e.endTime ? dayjs(e.endTime).format('YYYY-MM-DD') : '';
      this.doQuery().then(res => {
        this.hasNext = res.hasNext
        this.fixList = res.rows.map(item => {
          return { ...item, checked: false }
        })
      })
    },
    doQuery () {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        orderStartDate: this.startTime,
        orderEndDate: this.endTime,
        statusList: this.statusList
      }

      return list(params).then(res => {
        return Promise.resolve(res)
      }).catch(() => {
        this.loading = false
      })
    },
    //不同工单展示的数据字段
    isShowField (status) {
      if (status === REP_WORK_ORDER_STATUS.TO_ACCEPT.value || status === REP_WORK_ORDER_STATUS.TO_ACCEPT.REJECTED) return true;
      return false
    },

    //百分比-UI
    getOrderPercentage (status) {
      if (!status) return 0
      switch (status) {
        case this.repWorkOrderStatusList[0].value: return 0
        case this.repWorkOrderStatusList[1].value: return 0
        case this.repWorkOrderStatusList[2].value: return 50
        case this.repWorkOrderStatusList[3].value: return 70
        default: return 100
      }

    },
    //状态显示颜色
    getOrderStatusColor (status) {
      switch (status) {
        case this.repWorkOrderStatusList[0].value: return ''
        case this.repWorkOrderStatusList[1].value: return ''
        case this.repWorkOrderStatusList[2].value: return '#FF6262'
        case this.repWorkOrderStatusList[3].value: return '#2d8df2'
        case this.repWorkOrderStatusList[4].value: return '#FF9900'
        case this.repWorkOrderStatusList[5].value: return '#19BE6B'
        case this.repWorkOrderStatusList[6].value: return '#FF6262'
        default: return ''
      }
    },
    //状态-标签
    getStatusName (status) {
      const result = this.repWorkOrderStatusList.find(item => item.value === status)
      return result ? result.label : ''
    },
    timeFormat (date, time) {
      if (!date || !time) {
        return '-'
      }
      return date + ' ' + time.split(':')[0] + ":" + time.split(':')[1]
    }
  }
}
</script>

<style lang="scss" scoped>
.datePicker {
  position: absolute;
  left: 40rpx
}

.allowDispatch {
  border: 2rpx solid #2d8cf0;
  background: #2d8cf0;
}

.disAllowDispatch {
  border: 2rpx solid #2d8cf050;
  background: #2d8cf050;
}

.disAllowDelay {
  border: 2rpx solid #CCCCCC;
  color: #88888850;
  background: #F1F1F150;
}

.allowDelay {
  border: 2rpx solid #2d8cf0;
  color: #2d8cf0;
}
</style>
